/*
 * by wlh 
 * date 2025/09/16 09:59
 */
using MermaidParser;
using Sirenix.OdinInspector.Editor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

// 代表放置GraphView这个Canvas的EditorWindow
public class DialogueGraphWindow : EditorWindow
{
    //string mermaidCode = "graph TD\n\tA[Start] --> B{Process}\n\tB --> C[End]";

    public static DialogueGraphView graphView;
    //Toolbar toolbar;

    InspectObj_Left objLeft;

    //TextField mermaidTextField;
    private Group m_FixedGroup;

    string _fileName = "myDialogueGraph";

    // 通过Menu即可打开对应window, 注意这种函数必须是static函数
    [MenuItem("Graph/Open Dialogue Graph View")]
    public static void OpenDialogueGraphWindow()
    {
        // 定义了创建并打开Window的方法
        var window = GetWindow<DialogueGraphWindow>();
        window.titleContent = new GUIContent("Dialogue Graph");
    }

    private void OnEnable()
    {
        Debug.Log("New GraphView");
        graphView = new DialogueGraphView { name = "Dialogue Graph" };

        // 让graphView铺满整个Editor窗口
        graphView.StretchToParentSize();
        // 把它添加到EditorWindow的可视化Root元素下面
        //rootVisualElement.Add(_graphView);
    }
    
    // 关闭窗口时销毁graphView
    private void OnDisable()
    {
        //rootVisualElement.Remove(_graphView);
        //rightPanel.Add(_graphView);
        //rootVisualElement.Remove(toolbar);
        if (m_FixedGroup != null)
            rootVisualElement.Remove(m_FixedGroup);
    }

    private void CreateGUI()
    {
        objLeft = new(graphView);

        // 清空现有内容
        rootVisualElement.Clear();

        // 这个Toolbar类在UnityEditor.UIElements下
        var toolbar = new Toolbar();
        //创建lambda函数，代表点击按钮后发生的函数调用
        Button btn = new(clickEvent: () => { graphView.AddMermaidNode("id", NodeShape.Rect, "title"); })
        {
            text = "Add Node"
        };
        toolbar.Add(btn);
        rootVisualElement.Add(toolbar);

        // 添加TextField
        TextField fileNameTextField = new(label: "File Name");
        fileNameTextField.SetValueWithoutNotify(_fileName);// 类内私有成员_fileName = "New Narrative";
        fileNameTextField.MarkDirtyRepaint();
        fileNameTextField.RegisterValueChangedCallback(evt => _fileName = evt.newValue);
        toolbar.Add(fileNameTextField);

        toolbar.Add(new Button(() => graphView.AddGroup()) { text = "Add Group" });

        // 添加Button
        toolbar.Add(new Button(() => Test()) { text = "Test" });

        //CreateCommentBlock();

        // 创建主容器，使用左右布局
        TwoPaneSplitView splitView = new(0, 250, TwoPaneSplitViewOrientation.Horizontal);
        rootVisualElement.Add(splitView);

        var odinWin = OdinEditorWindow.InspectObject(objLeft);
        //splitView.Add(odinWin.rootVisualElement);
        /*
        // 左侧面板 - Mermaid代码编辑
        VisualElement leftPanel = new();
        leftPanel.style.paddingLeft = 5;
        leftPanel.style.paddingRight = 5;
        leftPanel.style.paddingTop = 5;
        leftPanel.style.paddingBottom = 5;

        // Mermaid代码输入区域
        mermaidTextField = new TextField("Mermaid Code")
        {
            multiline = true
        };
        mermaidTextField.style.height = 450;////
        //mermaidTextField.style.height = leftPanel.style.height.value.value - 100; //invalid
        // 设置左对齐到边沿
        mermaidTextField.style.marginLeft = -120;
        mermaidTextField.style.marginRight = 0;
        //mermaidTextField.style.marginBottom = 150; //invalid
        //mermaidTextField.style.paddingBottom = 50; //invalid
        mermaidTextField.style.alignSelf = Align.Stretch;

        leftPanel.Add(mermaidTextField);

        // 按钮区域
        VisualElement buttonContainer = new();
        buttonContainer.style.flexDirection = FlexDirection.Row;
        buttonContainer.style.justifyContent = Justify.SpaceAround;
        buttonContainer.style.marginTop = 10;

        var parseButton = new Button(Btn_TextToGraph) { text = "Parse to graph" };
        var createButton = new Button(Btn_CreateNodes) { text = "create graph nodes" };
        var saveButton = new Button(Btn_GraphToText) { text = "Save to text" };

        buttonContainer.Add(parseButton);
        buttonContainer.Add(createButton);
        buttonContainer.Add(saveButton);
        leftPanel.Add(buttonContainer);
        */
        VisualElement leftP = new();
        leftP.Add(odinWin.rootVisualElement);

        // 右侧面板 - 图形显示
        VisualElement rightPanel = new();
        rightPanel.style.flexGrow = 1;
        rightPanel.Add(graphView);

        // 将左右面板添加到分割视图
        splitView.Add(leftP);
        splitView.Add(rightPanel);

        // 添加示例代码
        //mermaidTextField.value = mermaidCode;
        
    }
    //"<br>"换行

    void Btn_CreateNodes()
    {
        // 创建不同类型的Mermaid节点
        graphView.AddMermaidNode("A", NodeShape.Rect, "节点节点节点节点节点节点", new Vector2(100, 100));
        graphView.AddMermaidNode("B", NodeShape.Circle, "开始或结束2", new Vector2(300, 100));
        graphView.AddMermaidNode("C", NodeShape.RoundRect, "开始或结束1", new Vector2(500, 100));
        graphView.AddMermaidNode("D", NodeShape.Rhombus, "判断或分支", new Vector2(200, 200));
        graphView.AddMermaidNode("E", NodeShape.Subroutine, "子图", new Vector2(300, 200));

        graphView.AddMermaidNode("F", NodeShape.Cylinder, "数据库", new Vector2(100, 400));
        graphView.AddMermaidNode("G", NodeShape.Stadium, "跑道形", new Vector2(300, 400));
    }

    //创建固定位置和大小的group。可作为输出窗口
    void CreateCommentBlock()
    {
        // 创建Comment Block
        m_FixedGroup = new Group//InspectorGroup
        {
            //autoUpdateGeometry = true,
            title = "Comment Block\n sss \n fff" +
            "\nfddddddddd" +
            "\nfdsafdsafdsa" +
            "\nfdsafdsa" +
            "\nfdsafdsa" +
            "dsafd"
        };
        // 可以改layer, 但是这里默认就比GraphView的优先级高，应该是深度递归的顺序导致
        //m_FixedGroup.layer = int.MaxValue; 
        m_FixedGroup.style.position = Position.Absolute;
        m_FixedGroup.style.right = 0;
        m_FixedGroup.style.top = 21;// 21是工具栏的高度
        // 尤其注意这句话，是加到EditorWindow里
        rootVisualElement.Add(m_FixedGroup);
    }

    void Test()
    {
        // 选中Node时，自然会高亮
        graphView.ClearSelection();
        Debug.Log("==="+graphView.nodes.Count());
        graphView.AddToSelection(graphView.nodes.AtIndex(2)); // 会变！选中的总是会被变为最后一个。
        Debug.Log("***"+graphView.nodes.Count());
        foreach (var node in graphView.nodes)
            Debug.Log($"{node.title}");
    }
}
